<template>
    <div>
        <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
        <div class="add">
            <div class="common-layout">
                <el-container>
                    <el-main>
                        <el-row>
                            <el-col :span="24">
                                <div class="grid-content ep-bg-purple">
                                    <h4>基本信息</h4>
                                    <el-form :inline="true" :model="salesQuotes" :rules="rules" status-icon
                                        ref="formRef">
                                        <el-form-item label="单据编号" prop="doCode">
                                            <el-input v-model="salesQuotes.doCode" style="width: 240px"
                                                placeholder="请输入单据编号" clearable :disabled="true" />
                                        </el-form-item>


                                        <!-- 客户 -->
                                        <el-form-item label="客户" prop="cid">
                                            <el-select v-model="salesQuotes.cid" placeholder="请选择客户"
                                                style="width: 240px" clearable filterable>
                                                <el-option v-for="customer in customerList" :key="customer.id"
                                                    :label="`${customer.code} - ${customer.name}`"
                                                    :value="customer.id" />
                                            </el-select>
                                        </el-form-item>

                                        <!-- 报价日期 -->
                                        <el-form-item label="报价日期" prop="bjDate">
                                            <el-date-picker v-model="salesQuotes.bjDate" type="date" placeholder="请选择日期"
                                                value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
                                        </el-form-item>

                                        <!-- 报价名称 -->
                                        <el-form-item label="报价名称" prop="bjName">
                                            <el-input v-model="salesQuotes.bjName" style="width: 240px"
                                                placeholder="请输入报价名称" />
                                        </el-form-item>

                                        <el-form-item label="单据备注" prop="notes">
                                            <el-input v-model="salesQuotes.notes" style="width: 240px"
                                                placeholder="请输入单据备注" />
                                        </el-form-item>

                                        <!-- 业务员 -->
                                        <el-form-item label="业务员" prop="uid">
                                            <el-select v-model="salesQuotes.uid" placeholder="请选择业务员" clearable
                                                filterable @change="" style="width: 240px;">
                                                <el-option v-for="item in userList" :key="item.id" :label="item.name"
                                                    :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>

                                        <!-- 部门 -->
                                        <el-form-item label="部门" prop="did">
                                            <el-select v-model="salesQuotes.did" placeholder="请选择部门"
                                                style="width: 240px;" clearable>
                                                <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name"
                                                    :value="dept.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-col>
                        </el-row>
                    </el-main>
                </el-container>
            </div>
        </div>
        <div>
            <div class="toolbar">
                <el-button type="primary">商品信息</el-button>
                <el-button @click="addGoodsRow">继续添加</el-button>
                <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
            </div>
            <div class="goods-table-container">
                <!-- 商品信息表格 -->
                <el-table :data="tableData" border style="width: 100%" class="goods-table"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <!-- 商品编码（带必填标识的下拉框） -->
                    <el-table-column label="商品编码" width="150">
                        <template #header>
                            <span class="required-label">商品编码</span>
                        </template>
                        <template #default="scope">
                            <el-select v-model="scope.row.code" placeholder="请选择商品"
                                @change="handleGoodsChange(scope.row)" clearable>
                                <el-option v-for="item in goodsList" :key="item.code"
                                    :label="`${item.code} - ${item.name}`" :value="item.code" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <!-- 商品名称 -->
                  <el-table-column label="商品名称" width="180">
                    <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
                    </el-table-column>

                    <!-- 仓库信息 -->
                    <el-table-column label="仓库" width="120" align="center">
                        <template #default="scope">{{ scope.row.warehouse || '主仓库' }}</template>
                    </el-table-column>

                    <!-- 即时库存 -->
                    <el-table-column label="即时库存" width="100" align="center">
                        <template #default="scope">{{ scope.row.stock || 0 }}</template>
                    </el-table-column>

                    <!-- 单位（带必填标识） -->
                    <el-table-column label="单位" width="80" align="center">
                        <template #header>
                            <span class="required-label">单位</span>
                        </template>
                        <template #default="scope"> {{ scope.row.unit || '件' }}</template>
                    </el-table-column>

                    <!-- 数量（带必填标识的输入框） -->
                    <el-table-column label="数量" width="120" align="center">
                        <template #header>
                            <span class="required-label">数量</span>
                        </template>
                        <template #default="scope">
                            <el-input-number 
                                v-model="scope.row.quantity" 
                                :min="1" 
                                controls-position="right"
                                style="width: 100px"
                                @change="calculateTaxPrice(scope.row)"> <!-- 新增事件绑定 -->
                            </el-input-number>
                        </template>
                    </el-table-column>

                    <!-- 实际报价（可输入） -->
                    <el-table-column label="实际报价" width="130" align="center">
                        <template #default="scope">
                            <el-input-number 
                                v-model="scope.row.actualPrice" 
                                :min="1" 
                                :precision="2"
                                controls-position="right" 
                                style="width: 100px"
                                @change="calculateTaxPrice(scope.row)"> <!-- 新增事件绑定 -->
                            </el-input-number>
                        </template>
                    </el-table-column>

                    <el-table-column label="税额" width="120" align="center">
                        <template #default="scope">
                            {{ scope.row.taxAmount?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="价税合计" width="130" align="center">
                        <template #default="scope">
                            {{ scope.row.taxTotal?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>

                    <!-- 历史报价（可点击链接） -->
                    <el-table-column label="历史报价" width="120" align="center">
                        <template #default="scope">
                            <el-link type="primary" @click="showHistory(scope.row)" v-if="scope.row.historyPrice">
                                {{ scope.row.historyPrice }}
                            </el-link>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>

                    <!-- 其他只读列 -->
                    <el-table-column v-for="col in readonlyColumns" :key="col.prop" :prop="col.prop" :label="col.label"
                        :width="col.width" align="center" />
                </el-table>
            </div>
        </div>
        <div class="total-summary">
            <div class="total-label">合计</div>
            <div class="total-amount">{{ formatTotal }}</div>
        </div>
    </div>

</template>


<script setup lang="ts">
import { ref, reactive, withKeys, watch, computed, onMounted } from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElInput, ElAutoResizer, ElTableV2 } from 'element-plus'
import type { FunctionalComponent } from 'vue'
import type { Column, InputInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import type { SalesQuotation } from '@/types/public-xs/salesDocuments';
import axios from 'axios';
import GoodsInfo from '@/test/GoodsInfo.vue';
import type { Goods } from '@/types/public-xs/Goods';
import type { SalesQuotationDetail } from '@/types/public-xs/salesDocuments';
import type { Customer } from '@/types/public-xs/Customer';
import { ElMessageBox, ElMessage } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs';
import type { User, Department } from '@/types/rs/User';
import request from '@/util/request';

let route=useRoute()
const formRef = ref<FormInstance>()
const handleHistory = (row: any) => {
    console.log('查看历史报价:', row)
}

let router = useRouter()

let doCode = ref('')
let salesQuotes = ref<SalesQuotation>({
    id: 0,
    bjDate: new Date,
    cid: null,
    bjName: '',
    uid: 1,
    status: 0,
    totalQuantity: 100,
    totalAmount: 100,
    totalTaxValue: 100,
    notes: '',
    createBy: '毕建峰',
    createTime: new Date(),
    updateBy: '毕建峰',
    updateTime: new Date(),
    isDelete: 0,
    doCode: doCode.value,
    did: 1,
    typeId: 1
})
let goodsList = ref<Goods[]>([])
let pageSize = ref(5)
let allPage = ref(0)
//动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

//查询业务员的方法
let userList = ref<User[]>([])
let selectUser = async () => {
    let response = await request.post('/per/user/getAll')
    userList.value = response.data.data
    console.log(userList.value)
}
selectUser()

let deptList = ref<Department[]>([])
let selectDept = async () => {
    let response = await request.post('/per/dept/getAll')
    deptList.value = response.data.data
    console.log(deptList.value)
}
selectDept()











//查询条件
const queryConditions = reactive({
    combine: '',
    kid: ''
})

async function fetchData(page: number) {
    try {
        const params = new URLSearchParams();
        params.append('pageNow', page.toString());
        params.append('pageSize', pageSize.value.toString());
        params.append('combine', queryConditions.combine);
        params.append('kid', queryConditions.kid);

        let response = await request.post('/basic/good/getAll', {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        });
        console.log("查询到的商品",response.data.data)
        goodsList.value = response.data.data.map((item: any) => ({
            id: item.id,
            code: item.code,
            name: item.name,
            unique: item.uname,
            tax: item.tax,
            stock: item.stock,
            kname: item.kname
        }));
        console.log("查询商品集合", goodsList.value)
        allPage.value = response.data.data.total || 0;
    } catch (error) {
        ElMessage.error('获取商品数据失败');
        tableData.value = [];
        allPage.value = 0;
        console.error('获取数据失败:', error);
    }
}

fetchData(1)



let addGoodsRow = () => {
    tableData.value.push({
        id: generateUUID(),
        goodId: 0,
        code: '',
        name: '',     // 商品编码（必填）
        quantity: 1,        // 数量（必填，默认1）
        actualPrice: 0,  // 实际报价
        historyPrice: '点击查看', // 历史报价
        tax: 13,        // 增值税率
        taxIncludedPrice: 0,  // 含税单价
        stock: 100,
        unit: '件',
        kname: '测试',
        taxAmount:0,
        taxTotal:0,
    })
}


let title = ref('修改销售报价单')







const handleAction = (action: string) => {
    switch (action) {
        case 'save':
            saveDetails()
            break
        case 'save-add':
            saveDetails()
            break
        case 'history':
            router.push('/home/salesQuotesInf')
            break;
    }
}


const validateInteger = (row: any) => {
    if (!Number.isInteger(row.quantity) || row.quantity <= 0) {
        ElMessage.warning('数量必须为大于零的整数')
        row.quantity = Math.max(1, Math.round(row.quantity))
    }
}

const rules = reactive<FormRules>({
    cid: [
        { required: true, message: '请选择客户', trigger: 'change', type: 'number' }
    ],
    bjDate: [
        { required: true, message: '请选择报价日期', trigger: 'change' }
    ],
    bjName: [
        { required: true, message: '请输入报价名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
    ],
    uid: [
        { required: true, message: '请选择业务员', trigger: 'change' }
    ],
    did: [
        { required: true, message: '请选择部门', trigger: 'change' }
    ]
})

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}


// 调试：观察 ruleForm 的变化
watch(salesQuotes, (newVal) => {
    console.log('报价单数据更新:', newVal)
}, { deep: true })


// 按钮配置
const mainActions = ref([
    {
        name: 'save',
        label: '保存',
        type: 'primary',
        icon: 'DocumentAdd'
    },
    {
        name: 'save-add',
        label: '保存新增',
        disabled: false
    },
    {
        name: 'audit',
        label: '审核',
        hidden: false
    },
    {
        name: 'history',
        label: '历史单据',
        badge: 3 // 角标数字
    }

])
const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0
        const v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
    })
}


const tableData = ref([{
    id: generateUUID(),
    goodId: 0,
    code: '',
    name: '',
    quantity: 1,
    actualPrice: 0,
    historyPrice: '点击查看',
    tax: 13,
    taxIncludedPrice: 0,
    stock: 100,
    unit: '件',
    kname: '测试',
    taxAmount: 0,
    taxTotal: 0

}])









// 只读列配置
const readonlyColumns = [
    { prop: 'kname', label: '商品种类', width: 120 },
    { prop: 'suggestedPrice', label: '建议报价', width: 120 },
    { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
    { prop: 'tax', label: '增值税税率 (%)', width: 150 }
]


// 商品选择处理
const handleGoodsChange = (row: any) => {
    console.log(row)
    console.log("selected")
    const selected = goodsList.value.find(item => item.code === row.code)
    console.log("选中的数据", selected)
    if (selected) {
        row.goodsName = selected.name
        row.code = selected.code
        row.goodId = selected.id;
        row.stock = selected.stock;
        row.unit = selected.unique
        row.tax = selected.tax;
        row.kname = selected.kname
        row.stock = Math.max(1, selected.stock || 1)
        calculateTaxPrice(row)
    } else {
        // 清空相关字段
        row.goodsName = ''
        row.unit = '件'
        row.stock = 0
        row.stock = 1
    }
    watch(() => [row.quantity, row.actualPrice], () => {
        calculateTaxPrice(row)
    }, { immediate: true })


}

//回显数据
const loadData = async () => {
  try {
    // 1. 加载主数据
    const mainRes = await request.get(`/xs/xs/selectSalesQuotesByCode?doCode=${route.params.doCode}`)
    salesQuotes.value = mainRes.data.data
    
    // 2. 加载明细数据
    const detailRes = await request.get(`/xs/xs/selectSalesQuotesDetailByCode?bjCode=${route.params.doCode}`)
    console.log(detailRes.data.data)
     // 3. 提取所有商品ID
    const goodIds = detailRes.data.data
      .map((item: any) => item.goodId)
      .filter((id: number) => id > 0);
    // 4. 批量查询商品信息
    const goodsRes = await request.post('/basic/good/getGoodList', goodIds );
    
    console.log("/goodsRes",goodsRes)
    // 5. 创建商品映射表
    const goodsMap = new Map();
    goodsRes.data.data.forEach((good: Goods) => {
      goodsMap.set(good.id, good);
    });

    // 6. 合并数据到表格
    tableData.value = detailRes.data.data.map((item: any) => {
      const good = goodsMap.get(item.goodId) || {};
      console.log("good对象",good)
      return {
        code: good.code || '未知编码',
        goodsName: good.name || '未知商品',
        quantity: item.quantity,
        actualPrice: item.actualPrice,
        unit: good.uname || '',
        stock: good.stock || 1000,
        goodId: item.goodId, // 保留原始ID用于后续操作
        tax: item.tax || good.tax, 
        kname: good.kname || item.kname || '-',  // 双重保障
      };
    });
    console.log("回显的表格数据",tableData.value)
    await selectCustomer()
    await fetchData(1)
    tableData.value.forEach(row => calculateTaxPrice(row))
    tableData.value = [...tableData.value] 
    console.log('最终表格数据:', tableData.value)
  } catch (error) {
    ElMessage.error('数据加载失败')
  }

}


onMounted(()=>{
    loadData()
})

const selectedRows = ref<any[]>([])

// 处理选中行变化
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的行')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 行吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // 通过ID过滤实现删除
        const selectedIds = new Set(selectedRows.value.map(row => row.id))
        tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))

        ElMessage.success('删除成功')
    } catch (error) {
        ElMessage.info('已取消删除')
    }
}




// 修改含税价计算方法
const calculateTaxPrice = (row: any) => {
    try {
        const unitPrice = Number(row.actualPrice) || 0
        const taxRate = (Number(row.tax) || 0) / 100
        const quantity = Number(row.quantity) || 0

        // 计算中间结果（保留4位小数）
        const unitTax = Number((unitPrice * taxRate).toFixed(4))
        row.taxAmount = Number((unitTax * quantity).toFixed(2))

        // 含税单价计算（四舍五入保留2位）
        row.taxIncludedPrice = Number((unitPrice + unitTax).toFixed(2))

        // 价税合计计算（四舍五入保留2位）
        row.taxTotal = Number((row.taxIncludedPrice * quantity).toFixed(2))
    } catch (e) {
        console.error('计算错误:', e)
        row.taxAmount = 0
        row.taxTotal = 0
    }
}

// 新增总税额计算属性
const totalTax = computed(() => {
    return tableData.value.reduce((sum, row) => {
        return sum + (Number(row.taxAmount) || 0)
    }, 0)
})

// 观察总税额变化
watch(totalTax, (newVal) => {
    salesQuotes.value.totalTaxValue = Number(newVal.toFixed(2))
})
// 显示历史报价
const showHistory = (row: any) => {
    console.log('显示历史报价:', row.code)
    // 实际应调用API获取历史数据
}

const totalAmount = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (Number(row.taxTotal) || 0) // 直接累加每行的价税合计值
  }, 0)
})

// 格式化金额显示
const formatTotal = computed(() => {
    return `¥${totalAmount.value.toFixed(2)}`
})

const totalQuantity = computed(() => {
    return tableData.value.reduce((sum, row) => {
        return sum + (Number.isInteger(row.quantity) ? Math.max(0, row.quantity) : 0)
    }, 0)
})

const generateDetails = () => {
    return tableData.value.map(item => ({
        id: 0,
        bjCode: salesQuotes.value.doCode,
        goodId: item.goodId,
        quantity: item.quantity,
        actualPrice: Number(item.actualPrice) || 0,
        discountRate: 0,
        notes: '第一次测试',
        createBy: '毕建峰',
        createTime: new Date,
        updateBy: '毕建峰',
        updateTime: new Date,
        isDelete: 0,
        taxAmount: Number(item.taxAmount.toFixed(2))
    })) as SalesQuotationDetail[]
}

// 创建空行模板
const createEmptyRow = () => ({
    id: generateUUID(),
    goodId: 0,
    code: '',
    name: '',
    quantity: 1,
    actualPrice: 0,
    historyPrice: '点击查看',
    tax: 13,
    taxIncludedPrice: 0,
    stock: 100,
    unit: '件',
    kname: '测试',
})



// 两个同时新增
const saveDetails = async () => {
    console.log('当前表格数据:', JSON.parse(JSON.stringify(tableData.value)))
    try {
        // 1. 校验主表单
        const formValid = await formRef.value?.validate()
        if (!formValid) return

        // 2. 校验商品表格数据
        if (tableData.value.length === 0) {
            ElMessage.warning('请至少添加一条商品信息')
            return
        }

        const invalidRows = tableData.value.filter(row =>
            !row.code ||
            !row.quantity ||
            !row.actualPrice ||
            row.quantity <= 0 ||
            row.actualPrice <= 0
        )

        if (invalidRows.length > 0) {
            ElMessage.error('以下商品信息不完整：')
            invalidRows.forEach(row => {
                if (!row.code) {
                    ElMessage.error(`第${tableData.value.indexOf(row) + 1}行：请选择商品编码`)
                }
                if (!row.quantity || row.quantity <= 0) {
                    ElMessage.error(`第${tableData.value.indexOf(row) + 1}行：数量必须大于0`)
                }
                if (!row.actualPrice || row.actualPrice <= 0) {
                    ElMessage.error(`第${tableData.value.indexOf(row) + 1}行：实际报价必须大于0`)
                }
            })
            return
        }

        // 3. 所有校验通过后提交
        const details = generateDetails()
        salesQuotes.value.totalAmount = totalAmount.value
        salesQuotes.value.totalQuantity = totalQuantity.value
        salesQuotes.value.totalTaxValue = Number(totalTax.value.toFixed(2))
        const response = await request.post('/xs/xs/updateSalesQuotes', {
            details: details,
            salesQuote: salesQuotes.value,
            doCode:salesQuotes.value.doCode
        })

        if (response.data.code == '200') {
            ElMessage.success('保存成功')
            router.push('/home/salesQuotesInf')
        }
    } catch (error) {
        ElMessage.error('保存失败,请完整填写单据信息')
    }
}



</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.required-label::after {
    content: "*";
    color: #f56c6c;
    margin-left: 4px;
}

.goods-table {
    margin-top: 20px;
}

.toolbar {
    margin-bottom: 15px;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
    text-align: center;
}

.total-summary {
    background: #fff8dc;
    /* 浅黄色背景 */
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    border: 1px solid #ebeef5;
    border-top: none;
}

.total-label {
    font-weight: 600;
    color: #606266;
    margin-right: 30px;
}

.total-amount {
    color: #f56c6c;
    min-width: 120px;
    text-align: right;
    font-family: Arial, sans-serif;
}

/* 错误状态样式 */
:deep(.el-form-item.is-error) {

    .el-input__inner,
    .el-select__wrapper {
        box-shadow: 0 0 3px rgba(245, 108, 108, .3);
    }
}

/* 表格错误行高亮 */
.el-table__row.error-row {
    td {
        background-color: #fff3f3 !important;

        .cell {
            color: #f56c6c;
            font-weight: 500;
        }
    }
}

/* 新增滚动容器样式 */
.goods-table-container {
    max-height: 400px;
    /* 可根据实际需求调整高度 */
    overflow-y: auto;
    margin-top: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

/* 调整表格样式 */
.goods-table {
    min-width: 1200px;
    /* 根据列宽总和设置最小宽度 */
    width: 100%;
}

/* 美化滚动条（可选） */
.goods-table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: #f5f5f5;
}

.goods-table-container::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: #c1c1c1;
}

.goods-table-container::-webkit-scrollbar-track {
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
}
</style>